package cn.hicard.risk.action.sys;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hicard.core.Page;
import cn.hicard.core.PageResult;
import cn.hicard.core.Where;
import cn.hicard.risk.entity.SysOperateLog;
import cn.hicard.risk.service.sys.SysLogService;
import cn.hicard.util.AppConfig;
import cn.hicard.util.DateHelp;
import cn.hicard.util.IOHelper;

/**
 * 系统操控Action，提供动态的系调整功能
 * @author zhangyu
 */
@Controller
@RequestMapping("/sys")
public class SystemAction {
	
	@Autowired
	private SysLogService sysLogService;
	
	/**
	 * 搜索日志
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/logs")
	public String searchLogs(@RequestParam(required=false,defaultValue="1") int index, 
			@RequestParam(required=false,defaultValue="20") int size, ModelMap map,
			@RequestParam(required=false)String operateType,
			@RequestParam(required=false)String operator,
			@RequestParam(required=false)String remark,
			@RequestParam(required=false)String dateStart,
			@RequestParam(required=false)String dateEnd
			) throws Exception{
		// 查询条件
		Where where=new Where(SysOperateLog.class);
		where.addEqual("operateType", operateType);
		where.addEqual("operator", operator);
		where.addLike("remark", remark);
		if(dateStart != null && !dateStart.isEmpty()){
			where.addGreaterEq("operateTime", dateStart+" 00:00:00");
		}
		if(dateEnd != null && !dateEnd.isEmpty()){
			where.addLessEq("operateTime", dateEnd+" 23:59:59");
		}	
		
		// 分页条件，Hibernate查询分页时页码从0开始
		Page page = new Page(index-1, size);		
		PageResult<SysOperateLog> pr = sysLogService.search(where, page);		
		map.addAttribute("list", pr.getDataList());
		map.addAttribute("totalcount", pr.getResultCount());		
		
		return "/sys/logs";
	}
	
	
	/**
	 * 系统运行状态信息
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/info")
	public String sysinfo(ModelMap map) throws Exception{
		long totalMemory = Runtime.getRuntime().totalMemory();
		long freeMemory = Runtime.getRuntime().freeMemory();
		String dateTime = DateHelp.dateTime();
		int threadCount = Thread.activeCount();
		map.addAttribute("totalMemory",totalMemory);
		map.addAttribute("freeMemory", freeMemory);
		map.addAttribute("dateTime", dateTime);
		map.addAttribute("threadCount",threadCount);
		
		
		
		
		return "/sys/info";
	}

	/**
	 * 运行垃圾回收器
	 * @return
	 */
	@RequestMapping("/jvmgc")
	public String jvmGC(){
		Runtime.getRuntime().gc();
		return "redirect:/sys/info.do";
	}
	
	/**
	 * 重新加载配置文件
	 * @param map
	 * @return
	 */
	@RequestMapping("/reloadcfg")
	public String reloadConfig(ModelMap map){
		AppConfig.load(AppConfig.DEFAULT_FILE);
		map.addAttribute("message", "配置文件已成功重新加载，并且立即生效！");
		return "redirect:/sys/info.do";
	}

	/**
	 * 返回服务器的日期时间
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/datetime")
	public String serverTime(){
		return DateHelp.dateTime();
	}
	
	@RequestMapping("/logfiles")
	public String listLogfile(ModelMap map){
		File logdir = new File(AppConfig.get("system.logdir"));
		String[] files = logdir.list();
		if(files==null)files=new String[0];
		// windows会排序，linux则是乱序，这里人工冒泡排序
		for (int i = 0; i < files.length-1; i++) {			
			for (int k = 0; k < files.length-i-1; k++) {
				if(files[k+1].compareTo(files[k])>0){
					String tmp = files[k];
					files[k] = files[k+1];
					files[k+1] = tmp;
				}
			}
		}
				
		map.addAttribute("list", files);
		return "/sys/logfiles";
	}
	
	@ResponseBody
	@RequestMapping("/dllogfile")
	public ResponseEntity<byte[]> downloadLogfile(@RequestParam String filename) throws Exception{
		String logdir = AppConfig.get("system.logdir");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));				
		File logfile = new File(logdir + filename);		
		ByteArrayOutputStream output = new ByteArrayOutputStream(1024*1024);
		IOHelper.writeTo(new FileInputStream(logfile), output);
		return new ResponseEntity<byte[]>(output.toByteArray(), headers, HttpStatus.CREATED);
	}
}
